package com.atguigu.paymentdemo.service.impl;

import com.atguigu.paymentdemo.entity.OrderInfo;
import com.atguigu.paymentdemo.entity.Product;
import com.atguigu.paymentdemo.enums.OrderStatus;
import com.atguigu.paymentdemo.mapper.OrderInfoMapper;
import com.atguigu.paymentdemo.mapper.ProductMapper;
import com.atguigu.paymentdemo.service.OrderInfoService;

import com.atguigu.paymentdemo.util.OrderNoUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Resource
    private ProductMapper productMapper;

    @Override
    public OrderInfo createOrderByProdectId(Product product,String userId) {
        
        //获取商品信息
        Product p = productMapper.selectById(product.getId());

        //生成订单
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderNo(OrderNoUtils.getOrderNo());//订单号
        orderInfo.setTitle(p.getTitle()+"支付订单");
        orderInfo.setProductId(p.getId());
        orderInfo.setTotalFee(p.getPrice().multiply(new BigDecimal(100)));
        orderInfo.setOrderStatus(OrderStatus.NOTPAY.getType());
        orderInfo.setUserId(userId);
        //TODO 存入数据库
        baseMapper.insert(orderInfo);


        return orderInfo;
    }

    /**
     * 存储订单二维码
     * @param orderNo
     */
    @Override
    public void callBackPayUpdate(String orderNo) {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no",orderNo);

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderStatus(OrderStatus.SUCCESS.getType());
        baseMapper.update(orderInfo,queryWrapper);
    }

    /**
     * 根据商品id查询未支付订单
     * 防止重复创建订单对象
     * @param productId
     * @return
     */
    private OrderInfo getNoPatOrderByProductId(Long productId) {
        QueryWrapper<OrderInfo> QueryWrapper = new QueryWrapper<>();
        QueryWrapper.eq("product_id",productId);
        QueryWrapper.eq("order_status",OrderStatus.NOTPAY.getType());

       // QueryWrapper.eq("user_id")

        OrderInfo orderInfo = baseMapper.selectOne(QueryWrapper);
        return orderInfo;
    }

    @Override
    public OrderInfo findOrderByOrderNo(String orderNo) {
        QueryWrapper<OrderInfo> QueryWrapper = new QueryWrapper<>();
        QueryWrapper.eq("order_no",orderNo);
        OrderInfo orderInfo = baseMapper.selectOne(QueryWrapper);
        return orderInfo;
    }

    @Override
    public OrderInfo getMyOrderInfo(String userId) {
        QueryWrapper<OrderInfo> QueryWrapper = new QueryWrapper<>();
        QueryWrapper.eq("user_id",userId);
        OrderInfo orderInfo = baseMapper.selectOne(QueryWrapper);
        return orderInfo;
    }


}
